package com.hb0730.boot.admin.modules.sci.util;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import jakarta.servlet.http.HttpServletResponse;
import lombok.experimental.UtilityClass;
import java.util.Map;

import static org.springframework.security.util.FieldUtils.getFieldValue;

@UtilityClass
public class ExportFileUtil {
        public static <T> void exportData(HttpServletResponse response, Map<String, String> values, List<T> dataList) throws IOException {
     // 设置 Excel 响应属性
        setExcelResponseProp(response, "导出文件");
        // 表头处理
        List<List<String>> head = values.entrySet().stream()
                .map(entry -> Collections.singletonList(entry.getValue())) // 每个表头项作为一个单独的列表
                .collect(Collectors.toList());
        // 数据处理
        List<List<String>> data = new ArrayList<>();
        if (dataList != null && !dataList.isEmpty()) {
            for (T dataItem : dataList) {
                List<String> row = new ArrayList<>();
                for (String field : values.keySet()) {
                    String value = null;
                    try {
                         Object fieldValue = getFieldValue(dataItem, field);
                        if (fieldValue instanceof String) {
                            value= (String) fieldValue;
                        } else if (fieldValue instanceof LocalDateTime) {
                            value=((LocalDateTime) fieldValue).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
                        } else {
                            value= fieldValue != null ? fieldValue.toString() : null;
                        }
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException("获取字段值失败", e);
                    }
                    row.add(value);
                }
                data.add(row);
            }
        }

        // 写入 Excel 文件
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .excelType(ExcelTypeEnum.XLSX)
                .sheet("Sheet1")
                .doWrite(data);
    }
        private void setExcelResponseProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }
}
